﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.UserCode;
using System.Collections.ObjectModel;
using System.Reflection;
using Microsoft.SharePoint.Administration;
using System.Runtime.InteropServices;

namespace CKS.Sandbox.Admin.Validators
{
    [GuidAttribute("DA813D39-3E79-4114-AAA4-9781037CDD63")]
    public class CoreValidator : SPSolutionValidator
    {
        #region Required stuff in the Constructor
        private const string validatorName = "CKS:Sandbox Validator";

        public CoreValidator() { }

        // need to use this base constructor
        public CoreValidator(SPUserCodeService ucs)
            : base(validatorName, ucs)
        {
            this.Signature = 13370;
        }
        #endregion

        /// <summary>
        /// Checks for Solution Id, RegEx matches and Blocked File Types
        /// </summary>
        /// <param name="properties"></param>
        public override void ValidateSolution(SPSolutionValidationProperties properties)
        {
            base.ValidateSolution(properties);
        }

        /// <summary>
        /// Checks for Assembly Public Key Token
        /// </summary>
        /// <param name="properties"></param>
        /// <param name="assembly"></param>
        public override void ValidateAssembly(SPSolutionValidationProperties properties, SPSolutionFile assembly)
        {

            string c_PublicKeyTokenString = "PublicKeyToken=";

            bool isValid = true;

            base.ValidateAssembly(properties, assembly);

            // extract the assembly from the SPSolutionFile object
            ReadOnlyCollection<byte> bytesObject = assembly.OpenBinary();
            byte[] bytes = new byte[bytesObject.Count];
            bytesObject.CopyTo(bytes, 0);

            // Using reflection, go get the assembly object
            Assembly assemblyObject = System.Reflection.Assembly.ReflectionOnlyLoad(bytes);

            #region Validate Assembly

            #region Public Key Token check
            if (assemblyObject.FullName.IndexOf(c_PublicKeyTokenString) != -1)
            {
                string PublicKeyToken = assemblyObject.FullName.Substring(assemblyObject.FullName.IndexOf(c_PublicKeyTokenString));

                if (PublicKeyToken == "Geoff")
                {
                    isValid = false;
                }
            }
            #endregion

            #endregion

            if (!isValid)
            {
                properties.Valid = false;
                properties.ValidationErrorMessage = "The assembly failed the CKS:Sandbox validation rules";
            }
        }
    }
}
